package com.best.oasis.settlement.web.action.security;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import com.best.oasis.settlement.common.entity.security.User;
import com.best.oasis.settlement.common.so.security.UserSO;
import com.best.oasis.settlement.common.vo.security.SelectedRoleGroupVO;
import com.best.oasis.settlement.common.vo.security.UserInfoFromLdapServerVO;
import com.best.oasis.settlement.common.vo.security.UserVO;
import com.best.oasis.settlement.service.base.BusinessException;
import com.best.oasis.settlement.service.security.UserService;
import com.best.oasis.settlement.util.convert.ConvertUtil;
import com.best.oasis.settlement.util.page.PageList;
import com.best.oasis.settlement.web.action.base.BaseActionImpl;

@RemotingDestination
@Service
public class UserActionImpl extends BaseActionImpl<UserVO, User> implements UserAction {

    @Autowired
    private UserService           userService;
    @Autowired
    private AuthenticationManager authManager;

    @Override
    public void afterConstruct() {
        super.setBaseService(userService);
    }

    /**
     * {@inheritDoc}
     */
    public Principal doAuthentication(String username, String password) {
        Authentication authentication = this.authManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return authentication;
    }

    /**
     * {@inheritDoc}
     */
    public boolean logout(Principal principal) {
        SecurityContextHolder.clearContext();
        return true;
    }

    /**
     * 用户管理模块中，用来记录当前用户被选中的用户组
     */
    public List<SelectedRoleGroupVO> getSelectedRoleGroup(Long id) {
        List<SelectedRoleGroupVO> selectedRoleGroupList = new ArrayList<SelectedRoleGroupVO>();
        selectedRoleGroupList = userService.getSelectedRoleGroup(id);
        return selectedRoleGroupList;
    }

    /**
     * 从LdapServer获得用户信息
     * 
     * @throws Exception
     */
    public UserInfoFromLdapServerVO getUserInfoFromLdapServer(String username) throws Exception {

        UserInfoFromLdapServerVO userInfoFromLdapServerVo = new UserInfoFromLdapServerVO();

        UserVO user = userService.getUserByUsername(username);
        if (user != null) {
            //messageFlg=2： 当前用户名对应的用户信息已经在本地数据库存在
            userInfoFromLdapServerVo.setMessageFlg(2);
            return userInfoFromLdapServerVo;
        }
        UserVO userVo = null;
        userVo = userService.getUserInfoFromLdapServer(username);
        if (userVo == null) {
            //messageFlg=1： 从LdapServer获得用户信息时，LdapServer数据不存在
            userInfoFromLdapServerVo.setMessageFlg(1);
            return userInfoFromLdapServerVo;
        }
        //messageFlg=0：不存在错误和异常，获取数据成功
        userInfoFromLdapServerVo.setMessageFlg(0);
        userInfoFromLdapServerVo.setUserVo(userVo);
        return userInfoFromLdapServerVo;
    }

    /**
     * 获得当前登录用户信息
     */
    public UserVO getLoginUser() {
        return userService.getLoginUser();
    }

    /**
     * 修改密码
     */
    public String updatePassword(String oldPassword, String newPassword) {
        Long id = userService.getLoginUser().getId();
        if (id != null) {
            UserVO oldUser = userService.get(id);

            if (userService.updatePassword(oldUser, oldPassword, newPassword)) {
                return SUCCESS;
            } else {
                return "failed";
            }

        } else
            return "failed";

    }

    @Override
    public UserVO create(UserVO vo) {
        userService.register(vo);
        return vo;
    }

    public UserVO update(UserVO vo) {
        UserVO oldUserVO = userService.get(vo.getId());

        if (oldUserVO == null) {
            vo = super.update(vo);
        } else {
            if (oldUserVO.getId().equals(vo.getId())) {

                vo.setPassword(oldUserVO.getPassword());
                userService.update(vo);
            } else {
                throw new BusinessException("", "登录名已存在!");
            }
        }
        return vo;
    }

    public void removeUserprofile(List<Long> userIds) {
        List<Long> result = ConvertUtil.toLongs(userIds);
        userService.remove(result);
    }

    /**
     * 根据so进行搜索T的对象，返回可以翻页的对象列表
     * 
     * @param so
     * @return
     */
    public PageList<UserVO> getUserPageList(UserSO so) {
        if (so == null) {
            so = new UserSO();
        }
        return userService.getUserPageList(so);
    }

    /**
     * 判断登录名是否存在
     */
    public Boolean userNameExist(String userName) {
        UserVO vo = userService.getUserByUsername(userName);
        if (vo == null) {
            return false;
        }
        return true;
    }
    /**
	 * 密码重置
	 */
	@Override
	 public UserVO resetPassword( UserVO user ) {
		return userService.resetPassword(user);
	}
}
